package com.pv.bfc.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.pv.bfc.dao.UserRepository;
import com.pv.bfc.model.BriefcaseUser;
import com.pv.bfc.model.Role;
import com.pv.bfc.web.validator.UserValidator;

@SuppressWarnings("deprecation")
public class NewUserController extends SimpleFormController {
	private static final String USER_NAME = "username";
	UserRepository userRepo;
	PasswordEncoder passEncoder = null;

	private static final Log logger = LogFactory
			.getLog(NewUserController.class);

	public NewUserController() {
		setCommandClass(BriefcaseUser.class);
		setSuccessView("usercreated");
		setValidator(new UserValidator());
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		logger.info("IN NewUserController - formBackingObject");
		Integer id = ServletRequestUtils.getIntParameter(request, USER_NAME);
		if (id != null && !"".equals(USER_NAME)) {
			return userRepo.retreiveUserByUserName(USER_NAME);
		} else {
			return super.formBackingObject(request);
		}

	}

	@Override
	protected void doSubmitAction(Object user) throws Exception {
		logger.info("IN NewUserController - doSubmitAction");

		Role role = null;

		BriefcaseUser bfcUser = (BriefcaseUser) user;
		logger.info("Encyptring the Password - " + bfcUser.getPassword());
		String encPassword = passEncoder.encodePassword(bfcUser.getPassword(),
				null);
		bfcUser.setPassword(encPassword);
		// bfcUser.setConfirmPassword(encPassword);
		userRepo.persistUser(bfcUser);

		// Add User Role to BRIEFCASE_ROLES table
		role = new Role();
		role.setUserName(bfcUser.getUserName());
		role.setRole("ROLE_USER");
		userRepo.addRoles(role);

		logger.info("OUT NewUserController - doSubmitAction");
	}

	public void setUserRepo(UserRepository userRepo) {
		this.userRepo = userRepo;
	}

	public void setPassEncoder(PasswordEncoder passEncoder) {
		this.passEncoder = passEncoder;
	}

}
